package com.solocredit.finance.utils.helper

import com.solocredit.finance.BuildConfig
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.utils.StringDeepCopy
import com.solocredit.finance.utils.language.LocaleContract
import com.solocredit.finance.utils.language.MultiLanguages
import org.json.JSONArray
import org.json.JSONObject
import kotlin.random.Random

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/14 12:04
 * @Annotation：自定义数据 帮助类
 */
object MullaCustomConfigsHelper {

    /**
     * 自定义数据来源
     *     1：客服配置
     *
     *      "customData": {
     *         "privacyPolicyLink": "https://moonvy.com/project/286a3d03-9556-4861-a38d-bbf7cc58cd43",
     *         "termsUseLink": "https://www.baidu.com",
     *         "isClearData": "YES",
     *         "defaultLanguage":"en",
     *         "licenseInfo": {
     *             "logo": "https://divoire.s3.af-south-1.amazonaws.com/pic/0eec2975dd8d4494a73e091fd4dcfb90.jpg",
     *             "desc": "This App is operated by",
     *             "companyName": "company name"
     *         },
     *         "licenseInfo_sw": {
     *             "logo": "https://divoire.s3.af-south-1.amazonaws.com/pic/0eec2975dd8d4494a73e091fd4dcfb90.jpg",
     *             "desc": "Programu hii inaendeshwa na",
     *             "companyName": "mtihani"
     *         },
     *         "noticeInfo": {
     *             "num":1,
     *             "isShow": "YES",
     *             "noticeTitle": "Notice",
     *             "noticeText": "By applying, the Applicant allows the lender or its authorized representatives to verify the information provided by him/her via call and field verification. The information provided by the Applicant shall include name, age, gender, emergency contact information, residence information, place of business and/or employment.\n\nEach Applicant shall only be allowed to register a maximum of One(1) userID or account in the Lender’s Software platform. Any additional User ID or account application will be subject for rejection or deletion by the lender without prior notice."
     *         },
     *         "noticeInfo_sw": {
     *             "num":1,
     *             "isShow": "YES",
     *             "noticeTitle": "Taarifa",
     *             "noticeText": "Lorem ipsum dolor sit amet, consectetur adipiscing elitsed do eiusmod tempor incididunt ut labore et doloremagna aliqua. Ut enim ad minim veniam, quis nostrudexercitation ullamco laboris nisi ut aliguip ex ea\n\ncommodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eufugiat nulla pariatur. Excepteur sint occaecat cupidatatnon proident, sunt in culpa qui offcia deserunt mollitanim id est laborum Lorem ipsum dolor sit amet, consectetur adipiscing elit."
     *         },
     *         "contactPonits": "8000",
     *         "accountPonits": "11000",
     *         "loanApplyPonits": "20000",
     *         "birthdayPonits": [
     *             "40000",
     *             "80000",
     *             "110000"
     *         ],
     *         "workDate": "Monday to Sunday",
     *         "workTime": "9:30am to 19:30pm.",
     *         "signPoints": [
     *             "400",
     *             "800",
     *             "2200",
     *             "1500",
     *             "1900",
     *             "2200",
     *             "4000"
     *         ],
     *         "taskPoints": [
     *             "4000",
     *             "20000",
     *             "40000"
     *         ],
     *         "luckyDrawUse": "8000",
     *         "luckyDrawGift": [
     *             "4000",
     *             "16000"
     *         ],
     *         "couponRateVip": [
     *             "1",
     *             "0.8",
     *             "0.6"
     *         ],
     *         "couponList": [
     *             {
     *                 "amount": "400",
     *                 "fullAmount": "36000",
     *                 "score": "360000",
     *                 "currency": "TZS"
     *             },
     *             {
     *                 "amount": "900",
     *                 "fullAmount": "90000",
     *                 "score": "900000",
     *                 "currency": "TZS"
     *             },
     *             {
     *                 "amount": "1800",
     *                 "fullAmount": "180000",
     *                 "score": "1800000",
     *                 "currency": "TZS"
     *             },
     *             {
     *                 "amount": "3600",
     *                 "fullAmount": "360000",
     *                 "score": "3600000",
     *                 "currency": "TZS"
     *             }
     *         ]
     *     },
     */

    /**
     * 获取客服配置
     */
    fun getMullaConfigData(): JSONObject? {
        val dataString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_COMMON)
        if (dataString.isEmpty()){
            return null
        }
        val data = JSONObject(dataString)
        if (data.has("customize")){
            return data.optJSONObject("customize")
        }
        return null
    }

    /**
     * 获取客服配置里自定义数据
     * customData
     */
    fun getMullaCustomData(): JSONObject?{
        val customize = getMullaConfigData()
        if (customize != null) {
            return customize.optJSONObject("customData")
        }
        return null
    }

    /**
     * 获取添加联系人对应获得的积分
     */
    fun getMullaAddPersonPoints(): String{
        var showPoints = "0"
        val customData = getMullaCustomData()
        if (customData != null) {
            showPoints = customData.optString("contactPonits")
        }
        return showPoints
    }

    /**
     * 获取添加绑卡账户对应获得的积分
     */
    fun getMullaAddAccountPoints(): String{
        var showPoints = "0"
        val customData = getMullaCustomData()
        if (customData != null) {
            showPoints = customData.optString("accountPonits")
        }
        return showPoints
    }

    /**
     * 获取贷款申请对应获得的积分
     */
    fun getMullaApplyPoints(): String{
        var showPoints = "0"
        val customData = getMullaCustomData()
        if (customData != null) {
            showPoints = customData.optString("loanApplyPonits")
        }
        return showPoints
    }

    /**
     * 根据签到天数 获取对应积分
     * 注意：签到天数 > 7 :
     *          可获得积分数 = 签到天数 % 7 - 1
     *      签到天数 <= 7:
     *          可获得积分数 = 签到天数 - 1
     */
    fun getMullaSignPointsBySignTime(signTime: Int): String{
        val customData = getMullaCustomData()
        if (customData != null){
            val signPoints = customData.optJSONArray("signPoints") ?: return "0"
            var signLength = signTime
            if (signLength > 7){
                signLength %= 7
            }
            if (signLength == 0){
                signLength = 7
            }
            return signPoints.optString(signLength - 1)
        }
        return "0"
    }

    /**
     * 获取任务积分
     */
    fun getMullaTaskPointsByTaskId(taskId: Int): String{
        val customData = getMullaCustomData()
        if (customData != null){
            val taskPoints = customData.optJSONArray("taskPoints") ?: return "0"
            return taskPoints.optString(taskId)
        }
        return "0"
    }

    /**
     * 获取抽奖需要消耗的积分
     */
    fun getMullaLuckyDrawPointsUse(): String{
        val customData = getMullaCustomData()
        if (customData != null) {
            return customData.optString("luckyDrawUse")
        }
        return "0"
    }

    /**
     * 获取抽奖获得的随机积分
     *
     * 规则：80% 奖励1
     *      20% 奖励2
     */
    fun getMullaLuckyDrawPoints(): String{
        val customData = getMullaCustomData()
        if (customData != null) {
            val pointsList = customData.optJSONArray("luckyDrawGift") ?: return "0"
            val randomIndex = Random.nextInt(100)
            if (randomIndex <= 80){
                return pointsList.optString(0)
            } else {
                return pointsList.optString(1)
            }
        }
        return "0"
    }

    /**
     * 获取优惠券列表
     *
     *  vip1 ： 显示 vip1 + vip2
     *  vip2 : 显示 vip2 + vip3
     *  vip3 ：显示 vip3
     */

    fun getMullaCouponList(): ArrayList<JSONObject>{
        val customData = getMullaCustomData()
        val couponList = arrayListOf<JSONObject>()
        customData?.let { data ->
            val couponRateVip = data.optJSONArray("couponRateVip")
            couponRateVip?.let { rateVip ->
                val couponRateVip1 = rateVip.optDouble(0,1.0)
                val couponRateVip2 = rateVip.optDouble(1,1.0)
                val couponRateVip3 = rateVip.optDouble(2,1.0)

                val vip1CouponList = arrayListOf<JSONObject>()
                val vip2CouponList = arrayListOf<JSONObject>()
                val vip3CouponList = arrayListOf<JSONObject>()
                val couponArray = data.optJSONArray("couponList")
                couponArray?.let {

                    val vip1Array = JSONArray(StringDeepCopy(it.toString()).content)
                    for (i in 0..<vip1Array.length()){
                        val item = vip1Array.optJSONObject(i)
                        item.put("score",(item.optDouble("score") * couponRateVip1).toInt())
                        item.put("vip","VIP1")
                        item.put("isExchange",getMullaUserVip() == 1)
                        vip1CouponList.add(item)
                    }


                    val vip2Array = JSONArray(StringDeepCopy(couponArray.toString()).content)
                    for (i in 0..<vip2Array.length()){
                        val item = vip2Array.optJSONObject(i)
                        item.put("score",(item.optDouble("score") * couponRateVip2).toInt())
                        item.put("vip","VIP2")
                        item.put("isExchange",getMullaUserVip() == 2)
                        vip2CouponList.add(item)
                    }

                    val vip3Array = JSONArray(StringDeepCopy(couponArray.toString()).content)
                    for (i in 0..<vip3Array.length()){
                        val item = vip3Array.optJSONObject(i)
                        item.put("score",(item.optDouble("score") * couponRateVip3).toInt())
                        item.put("vip","VIP3")
                        item.put("isExchange",getMullaUserVip() == 3)
                        vip3CouponList.add(item)
                    }
                }
                when(getMullaUserVip()){
                    1 -> {
                        couponList.addAll(vip1CouponList)
                        couponList.addAll(vip2CouponList)
                    }
                    2 -> {
                        couponList.addAll(vip2CouponList)
                        couponList.addAll(vip3CouponList)
                    }
                    else -> {
                        couponList.addAll(vip3CouponList)
                    }
                }
            }
        }
        return couponList
    }

    /**
     * 根据VIP等级 获取生日福利对应的积分
     */
    fun getMullaBirthdayBenefitsPoints(): String{
        val vip = getMullaUserVip()
        val customData = getMullaCustomData()
        if (customData != null) {
            val birthdayPonits = customData.optJSONArray("birthdayPonits") ?: return "0"
            return birthdayPonits.optString(vip - 1)
        }
        return "0"
    }

    /**
     * 获取用户VIP等级 1,2,3
     */
    fun getMullaUserVip(): Int{
        //用户VIP等级在首页获取产品列表处保存
        val vip = SharedHelper.getMullaSPInt(SharedHelper.MULLA_SPKEY.MULLA_VIP)
        if (vip == 0){
            return 1
        }
        return vip
    }

    /**
     * 获取隐私协议链接
     */
    fun getMullsPrivacyPolicyLink(): String{
        val customData = getMullaCustomData() ?: return ""
        return customData.optString("privacyPolicyLink","")
    }

    /**
     * 获取用户使用协议
     */
    fun getMullaTermsUseLink(): String{
        val customData = getMullaCustomData() ?: return ""
        if (customData.has("termsUseLink")){
            return customData.optString("termsUseLink","")
        }
        return ""
    }

    /**
     * 是否显示清空数据按钮
     */
    fun isMullaClearUserData(): Boolean{
        val customData = getMullaCustomData() ?: return false
        if (customData.has("isClearData")){
            return customData.optString("isClearData","NO") == "YES"
        }
        return false
    }

    /**
     * 获取牌照信息
     */
    fun getMullaLicenseInfo(): JSONObject?{
        val customData = getMullaCustomData() ?: return null
        var licenseData: JSONObject? = null
        if (customData.has("licenseInfo")){
            licenseData = customData.optJSONObject("licenseInfo")
        }

        //是否是 斯瓦希里语
        val curtLocale = MultiLanguages.getAppLanguage(MyApp.app.getAppContext())
        if (customData.has("licenseInfo_sw") && curtLocale.language == LocaleContract.getSwahiliLocale().language){
            licenseData = customData.optJSONObject("licenseInfo_sw")
        }
       return licenseData
    }

    /**
     * 获取配置的默认语言类型：坦桑地区需要语言切换功能
     * en、sw
     */
    fun getMullaConfigLanguage(): String{
        val customData = getMullaCustomData() ?: return ""
        return customData.optString("defaultLanguage","")
    }

    /**
     * 审核中、放款中是否显示公告信息
     */
    fun isMullaAuditNotice(): Boolean{
        val customData = getMullaCustomData() ?: return false
        if (customData.has("noticeInfo")){
            val noticeInfo = customData.optJSONObject("noticeInfo") ?: return false
            return noticeInfo.optString("isShow","NO") == "YES"
        }
        return false
    }

    /**
     * 获取 审核中、放款中 显示的公告信息
     */
    fun getMullaAuditNoticeInfo(): JSONObject?{
        val customData = getMullaCustomData() ?: return null

        var noticeData: JSONObject? = null
        if (customData.has("noticeInfo")){
            //默认为英语
            noticeData = customData.optJSONObject("noticeInfo")
        }

        //是否是 斯瓦希里语
        val curtLocale = MultiLanguages.getAppLanguage(MyApp.app.getAppContext())
        if (customData.has("noticeInfo_sw") && curtLocale.language == LocaleContract.getSwahiliLocale().language){
            noticeData = customData.optJSONObject("noticeInfo_sw")
        }
        return noticeData
    }

    /**
     * 获取版本更新信息
     */
    fun getMullaVersionObject(): JSONObject?{
        val customData = getMullaCustomData() ?: return null
        if (!customData.has("release")){
            return null
        }
        var versionData: JSONObject? = null
        if (customData.has("release")){
            versionData = customData.optJSONObject("release")
        }
        //是否是 斯瓦希里语
        val curtLocale = MultiLanguages.getAppLanguage(MyApp.app.getAppContext())
        if (customData.has("release_sw") && curtLocale.language == LocaleContract.getSwahiliLocale().language){
            versionData = customData.optJSONObject("release_sw")
        }
        return versionData
    }

    /**
     * 获取是否有强制更新（启动页使用）
     *  "isMustUpdate":true,
     *  "versionCode":"1",
     *  "versionName":"1.0.0",
     *  "versionRemark":"1xxx$2xxx$3xxx"
     */
    fun isMullaVersionUpdateMust(): Boolean {
        val versionObj = getMullaVersionObject() ?: return false
        val versionCode = versionObj.optInt("versionCode",1)
        val isMustUpdate = versionObj.optBoolean("isMustUpdate",false)
        return BuildConfig.VERSION_CODE < versionCode && isMustUpdate
    }

    /**
     * 获取是否有更新（首页使用）
     */
    fun isMullaVersionUpdate(): Boolean{
        val versionObj = getMullaVersionObject() ?: return false
        val versionCode = versionObj.optInt("versionCode",1)
        return BuildConfig.VERSION_CODE < versionCode
    }

    /**
     * SMS Content 关键字过滤
     */
    fun getMullaMSGContentKeys(): ArrayList<String>?{
        val customData = getMullaCustomData() ?: return null
        if (customData.has("smsContentKeys")){
            val msgContentKeys = customData.optJSONArray("msgContentKeys")
            if (msgContentKeys != null) {
                val list = ArrayList<String>()
                for (i in 0..<msgContentKeys.length()){
                    list.add(msgContentKeys.optString(i))
                }
                return list
            }
        }
        return null
    }


    /**
     * SMS Mobile 关键字过滤
     */
    fun getMullaMSGMobileKeys(): ArrayList<String>?{
        val customData = getMullaCustomData() ?: return null
        if (customData.has("msgMobileKeys")){
            val msgMobileKeys = customData.optJSONArray("msgMobileKeys")
            if (msgMobileKeys != null) {
                val list = ArrayList<String>()
                for (i in 0..<msgMobileKeys.length()){
                    list.add(msgMobileKeys.optString(i))
                }
                return list
            }
        }
        return null
    }
}